package cn.edu.imut.service;

import cn.edu.imut.bean.CartBean;
import cn.edu.imut.bean.ProductBean;
import cn.edu.imut.dao.CartDao;
import cn.edu.imut.dao.ProductDao;

import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/*
### 五、购物车表 (gs_cart)
| 字段名          | 数据类型        | 说明                     |
|-----------------|-----------------|--------------------------|
| user_id         | INT            | 外键，关联用户表（user_id） |
| product_id      | INT            | 外键，关联商品表（product_id） |
| product_quantity| INT            | 商品数量                 |
| product_name    | VARCHAR(100)   | 商品名称（冗余字段，加速查询） |
| product_category| INT            | 商品分类ID（冗余字段）   |
| total_price     | DECIMAL(10, 2) | 商品小计金额             |
| added_time      | DATETIME       | 加入购物车的时间         |
 */

public class CartService {
    //商品添加购物车功能
    public void AddToCart(int user_id){
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要加入购物车的商品ID:");
        String pid = sc.next();
        System.out.print("请输入商品数量:");
        String pqy = sc.next();
        try {
            int product_id = Integer.parseInt(pid);
            int product_quantity = Integer.parseInt(pqy);
            ProductDao productDao = new ProductDao();
            ProductBean productBean = productDao.getProductDetails(product_id);
            System.out.println(productBean);
            Double total_price = product_quantity * productBean.getPrice();
            LocalDateTime now = LocalDateTime.now();
            CartDao cartDao = new CartDao();
            CartBean cartBean = new CartBean(user_id,product_id,product_quantity,productBean.getProductName(),
                    productBean.getCategoryId(),total_price,now);
            cartDao.addCart(cartBean);
            System.out.println("商品已添加到购物车。");
        } catch (NumberFormatException e) {
            System.out.println("请正确输入(商品id和数量只能输入数字)!");
        } catch (Exception e) {
            System.out.println("不存在该商品!");
            throw new RuntimeException(e);
        }
    }

    //查看购物车商品
    public void ShowProductbyCart(int user_id){
        List<CartBean> listCart = new CartDao().getCartByUserId(user_id);
        for (int i = 0; i < listCart.size(); i++) {
            CartBean cartBean = listCart.get(i);
            System.out.println("商品ID:"+cartBean.getProduct_Id()+"\t商品名称:"+cartBean.getProduct_name()+
                    "\t商品数量:"+cartBean.getProduct_quantity()+"\t商品总金额:"+cartBean.getTotal_price()
                    +"\t加入时间:"+cartBean.getAddedTime());
        }
    }
    //修改购物车商品数量
    public void UpdateProductByCart(int user_id){
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要修改购物车中商品ID:");
        String pid = sc.next();
        System.out.print("请输入修改后商品数量:");
        String pqy = sc.next();
        try {
            int product_id = Integer.parseInt(pid);
            int product_quantity = Integer.parseInt(pqy);
            ProductDao productDao = new ProductDao();
            ProductBean productBean = productDao.getProductDetails(product_id);
            Double total_price = product_quantity * productBean.getPrice();
            CartDao cartDao = new CartDao();
            boolean flag = cartDao.updateProductQuantity(user_id,product_id,product_quantity,total_price);
            if (flag) {
                System.out.println("购物车中商品数量已修改。");
            }
        } catch (NumberFormatException e) {
            System.out.println("请正确输入(商品id和数量只能输入数字)!");
        }
    }
    //删除购物车中商品
    public void RemoveProductByCart(int user_id){
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要删除购物车中商品ID:");
        String pid = sc.next();
        try {
            int product_id = Integer.parseInt(pid);
            CartDao cartDao = new CartDao();
            boolean flag = cartDao.deleteCartByUserIdAndProductId(user_id,product_id);
            if (flag) {
                System.out.println("购物车中商品已删除。");
            }
        } catch (NumberFormatException e) {
            System.out.println("请正确输入(商品id和数量只能输入数字)!");
        }
    }
    private List<CartBean> cartDatabase = new ArrayList<>();

    /**
     * 添加商品到购物车
     */
    public void addToCart(int userId, ProductBean product, int quantity) {
        double totalPrice = product.getPrice() * quantity;
        CartBean cartItem = new CartBean(
                userId,
                product.getProductId(),
                quantity,
                product.getProductName(),
                product.getCategoryId(),
                totalPrice,
                LocalDateTime.now()
        );
        cartDatabase.add(cartItem);
        System.out.println("商品已成功加入购物车: " + cartItem);
    }

    /**
     * 显示购物车内容
     */
    public List<CartBean> viewCart(int userId) {
        List<CartBean> userCart = new ArrayList<>();
        for (CartBean cartItem : cartDatabase) {
            if (cartItem.getUser_Id() == userId) {
                userCart.add(cartItem);
            }
        }
        return userCart;
    }

    /**
     * 移除购物车商品
     */
    public void removeFromCart(int userId, int productId) {
        cartDatabase.removeIf(cartItem -> cartItem.getUser_Id() == userId && cartItem.getUser_Id() == productId);
        System.out.println("商品已从购物车移除。");
    }

    /**
     * 清空购物车
     */
    public void clearCart(int userId) {
        cartDatabase.removeIf(cartItem -> cartItem.getUser_Id() == userId);
        System.out.println("购物车已清空。");
    }
}
